#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""配置管理工具模块"""

import os
import json
import yaml
import configparser
import logging
import copy
import sys
from typing import Any, Dict, List, Optional, Tuple, Union, Callable, Set
import threading


class ConfigFileNotFoundError(Exception):
    """配置文件未找到异常"""
    pass


class ConfigParseError(Exception):
    """配置解析错误异常"""
    pass


class ConfigValidationError(Exception):
    """配置验证错误异常"""
    pass


class ConfigManager:
    """配置管理器，支持JSON、YAML和INI格式的配置文件"""
    
    def __init__(self, config_dir: Optional[str] = None, default_config: Optional[Dict[str, Any]] = None):
        """初始化配置管理器
        
        Args:
            config_dir: 配置目录路径，如果为None则使用默认目录
            default_config: 默认配置
        """
        # 确定配置目录
        self._config_dir = config_dir
        if config_dir is None:
            # 使用用户主目录下的.config目录作为默认配置目录
            self._config_dir = os.path.join(os.path.expanduser("~"), ".config", "kljmpythonied")
        
        # 确保配置目录存在
        os.makedirs(self._config_dir, exist_ok=True)
        
        # 存储默认配置
        self._default_config = default_config or {}
        # 存储当前配置
        self._config = copy.deepcopy(self._default_config)
        # 配置文件路径
        self._config_file_path: Optional[str] = None
        # 线程锁，保证线程安全
        self._lock = threading.RLock()
        # 验证器字典
        self._validators: Dict[str, Callable] = {}
        # 变更监听器
        self._change_listeners: List[Callable] = []
    
    @property
    def config_dir(self) -> str:
        """获取配置目录
        
        Returns:
            str: 配置目录路径
        """
        return self._config_dir
    
    @property
    def config_file_path(self) -> Optional[str]:
        """获取配置文件路径
        
        Returns:
            Optional[str]: 配置文件路径
        """
        return self._config_file_path
    
    @property
    def config(self) -> Dict[str, Any]:
        """获取当前配置的深拷贝
        
        Returns:
            Dict[str, Any]: 配置字典
        """
        with self._lock:
            return copy.deepcopy(self._config)
    
    def load(self, config_file: Optional[str] = None, config_format: Optional[str] = None) -> bool:
        """加载配置文件
        
        Args:
            config_file: 配置文件路径，如果为None则使用上次加载的路径
            config_format: 配置文件格式（json/yaml/ini），如果为None则根据文件扩展名判断
            
        Returns:
            bool: 是否加载成功
        """
        # 确定配置文件路径
        if config_file is None:
            if self._config_file_path is None:
                raise ConfigFileNotFoundError("No config file specified")
            config_file = self._config_file_path
        
        # 检查文件是否存在
        if not os.path.exists(config_file):
            raise ConfigFileNotFoundError(f"Config file not found: {config_file}")
        
        # 确定配置文件格式
        if config_format is None:
            # 根据文件扩展名判断
            _, ext = os.path.splitext(config_file)
            ext = ext.lower()[1:]  # 去除点号
            config_format = ext
        
        # 加载配置文件
        try:
            with self._lock:
                self._config_file_path = config_file
                self._config = copy.deepcopy(self._default_config)
                
                # 根据格式加载配置
                if config_format == 'json':
                    with open(config_file, 'r', encoding='utf-8') as f:
                        loaded_config = json.load(f)
                elif config_format == 'yaml' or config_format == 'yml':
                    with open(config_file, 'r', encoding='utf-8') as f:
                        loaded_config = yaml.safe_load(f)
                elif config_format == 'ini':
                    config_parser = configparser.ConfigParser()
                    config_parser.read(config_file, encoding='utf-8')
                    loaded_config = self._configparser_to_dict(config_parser)
                else:
                    raise ConfigParseError(f"Unsupported config format: {config_format}")
                
                # 合并配置
                if loaded_config:
                    self._merge_config(self._config, loaded_config)
                
                # 验证配置
                self._validate_config()
                
                # 触发变更事件
                self._notify_change_listeners()
                
            return True
        except (json.JSONDecodeError, yaml.YAMLError, configparser.Error) as e:
            raise ConfigParseError(f"Failed to parse config file: {str(e)}")
        except Exception as e:
            raise ConfigParseError(f"Failed to load config file: {str(e)}")
    
    def save(self, config_file: Optional[str] = None, config_format: Optional[str] = None) -> bool:
        """保存配置到文件
        
        Args:
            config_file: 配置文件路径，如果为None则使用上次加载的路径
            config_format: 配置文件格式（json/yaml/ini），如果为None则根据文件扩展名判断
            
        Returns:
            bool: 是否保存成功
        """
        # 确定配置文件路径
        if config_file is None:
            if self._config_file_path is None:
                raise ConfigFileNotFoundError("No config file specified")
            config_file = self._config_file_path
        
        # 确保目录存在
        config_dir = os.path.dirname(config_file)
        if config_dir and not os.path.exists(config_dir):
            os.makedirs(config_dir, exist_ok=True)
        
        # 确定配置文件格式
        if config_format is None:
            # 根据文件扩展名判断
            _, ext = os.path.splitext(config_file)
            ext = ext.lower()[1:]  # 去除点号
            config_format = ext if ext else 'json'  # 默认使用json格式
        
        # 保存配置文件
        try:
            with self._lock:
                # 验证配置
                self._validate_config()
                
                # 根据格式保存配置
                if config_format == 'json':
                    with open(config_file, 'w', encoding='utf-8') as f:
                        json.dump(self._config, f, ensure_ascii=False, indent=2)
                elif config_format == 'yaml' or config_format == 'yml':
                    with open(config_file, 'w', encoding='utf-8') as f:
                        yaml.dump(self._config, f, allow_unicode=True, default_flow_style=False)
                elif config_format == 'ini':
                    config_parser = self._dict_to_configparser(self._config)
                    with open(config_file, 'w', encoding='utf-8') as f:
                        config_parser.write(f)
                else:
                    raise ConfigParseError(f"Unsupported config format: {config_format}")
                
                # 更新配置文件路径
                self._config_file_path = config_file
            
            return True
        except Exception as e:
            raise ConfigParseError(f"Failed to save config file: {str(e)}")
    
    def get(self, key: str, default: Any = None, separator: str = '.') -> Any:
        """获取配置项的值
        
        Args:
            key: 配置项键名，可以使用点号分隔的嵌套键
            default: 默认值
            separator: 嵌套键分隔符
            
        Returns:
            Any: 配置项的值或默认值
        """
        with self._lock:
            # 解析键名
            keys = key.split(separator)
            
            # 遍历嵌套配置
            current = self._config
            for k in keys:
                if isinstance(current, dict) and k in current:
                    current = current[k]
                else:
                    return default
            
            return current
    
    def set(self, key: str, value: Any, separator: str = '.') -> None:
        """设置配置项的值
        
        Args:
            key: 配置项键名，可以使用点号分隔的嵌套键
            value: 配置项的值
            separator: 嵌套键分隔符
        """
        with self._lock:
            # 解析键名
            keys = key.split(separator)
            
            # 遍历嵌套配置并设置值
            current = self._config
            for i, k in enumerate(keys):
                if i == len(keys) - 1:
                    # 最后一个键，设置值
                    current[k] = value
                else:
                    # 不是最后一个键，确保是字典
                    if not isinstance(current.get(k), dict):
                        current[k] = {}
                    current = current[k]
            
            # 验证配置
            self._validate_config()
            
            # 触发变更事件
            self._notify_change_listeners()
    
    def remove(self, key: str, separator: str = '.') -> bool:
        """移除配置项
        
        Args:
            key: 配置项键名，可以使用点号分隔的嵌套键
            separator: 嵌套键分隔符
            
        Returns:
            bool: 是否移除成功
        """
        with self._lock:
            # 解析键名
            keys = key.split(separator)
            
            # 遍历嵌套配置并移除值
            current = self._config
            parent = None
            last_key = None
            
            for k in keys:
                if not isinstance(current, dict) or k not in current:
                    return False
                
                parent = current
                last_key = k
                current = current[k]
            
            # 移除键
            if parent is not None and last_key is not None:
                del parent[last_key]
                
                # 触发变更事件
                self._notify_change_listeners()
                
            return True
    
    def has(self, key: str, separator: str = '.') -> bool:
        """检查配置项是否存在
        
        Args:
            key: 配置项键名，可以使用点号分隔的嵌套键
            separator: 嵌套键分隔符
            
        Returns:
            bool: 配置项是否存在
        """
        with self._lock:
            # 解析键名
            keys = key.split(separator)
            
            # 遍历嵌套配置
            current = self._config
            for k in keys:
                if isinstance(current, dict) and k in current:
                    current = current[k]
                else:
                    return False
            
            return True
    
    def merge(self, config: Dict[str, Any]) -> None:
        """合并配置
        
        Args:
            config: 要合并的配置字典
        """
        with self._lock:
            self._merge_config(self._config, config)
            
            # 验证配置
            self._validate_config()
            
            # 触发变更事件
            self._notify_change_listeners()
    
    def reset(self) -> None:
        """重置配置为默认值"""
        with self._lock:
            self._config = copy.deepcopy(self._default_config)
            
            # 触发变更事件
            self._notify_change_listeners()
    
    def clear(self) -> None:
        """清空配置"""
        with self._lock:
            self._config = {}
            
            # 触发变更事件
            self._notify_change_listeners()
    
    def get_keys(self, prefix: str = '', separator: str = '.') -> List[str]:
        """获取所有配置项的键名
        
        Args:
            prefix: 前缀
            separator: 嵌套键分隔符
            
        Returns:
            List[str]: 键名列表
        """
        result = []
        
        with self._lock:
            # 如果有前缀，先获取前缀对应的配置
            if prefix:
                config = self.get(prefix, {}, separator)
                if not isinstance(config, dict):
                    return result
            else:
                config = self._config
            
            # 递归获取所有键名
            self._get_all_keys(config, prefix, separator, result)
        
        return result
    
    def _get_all_keys(self, config: Dict[str, Any], prefix: str, separator: str, result: List[str]) -> None:
        """递归获取所有键名
        
        Args:
            config: 配置字典
            prefix: 当前前缀
            separator: 嵌套键分隔符
            result: 结果列表
        """
        for key, value in config.items():
            full_key = f"{prefix}{separator}{key}" if prefix else key
            
            if isinstance(value, dict):
                # 递归获取嵌套字典的键名
                self._get_all_keys(value, full_key, separator, result)
            else:
                # 添加键名到结果列表
                result.append(full_key)
    
    def register_validator(self, key: str, validator: Callable) -> None:
        """注册配置验证器
        
        Args:
            key: 配置项键名
            validator: 验证函数，接收配置值，返回True表示验证通过
        """
        if callable(validator):
            with self._lock:
                self._validators[key] = validator
    
    def unregister_validator(self, key: str) -> None:
        """取消注册配置验证器
        
        Args:
            key: 配置项键名
        """
        with self._lock:
            if key in self._validators:
                del self._validators[key]
    
    def _validate_config(self) -> None:
        """验证配置"""
        for key, validator in self._validators.items():
            try:
                value = self.get(key)
                if not validator(value):
                    raise ConfigValidationError(f"Invalid value for config '{key}': {value}")
            except ConfigValidationError:
                raise
            except Exception as e:
                raise ConfigValidationError(f"Failed to validate config '{key}': {str(e)}")
    
    def add_change_listener(self, listener: Callable) -> None:
        """添加配置变更监听器
        
        Args:
            listener: 监听器函数，在配置变更时调用
        """
        if callable(listener):
            with self._lock:
                if listener not in self._change_listeners:
                    self._change_listeners.append(listener)
    
    def remove_change_listener(self, listener: Callable) -> None:
        """移除配置变更监听器
        
        Args:
            listener: 监听器函数
        """
        with self._lock:
            if listener in self._change_listeners:
                self._change_listeners.remove(listener)
    
    def _notify_change_listeners(self) -> None:
        """通知所有配置变更监听器"""
        # 复制监听器列表，避免在调用过程中修改列表
        listeners = self._change_listeners.copy()
        
        for listener in listeners:
            try:
                listener()
            except Exception as e:
                logging.error(f"Error in config change listener: {str(e)}")
    
    def _merge_config(self, target: Dict[str, Any], source: Dict[str, Any]) -> None:
        """深度合并配置字典
        
        Args:
            target: 目标配置字典
            source: 源配置字典
        """
        for key, value in source.items():
            if key in target and isinstance(target[key], dict) and isinstance(value, dict):
                # 递归合并嵌套字典
                self._merge_config(target[key], value)
            else:
                # 直接覆盖
                target[key] = value
    
    def _configparser_to_dict(self, config_parser: configparser.ConfigParser) -> Dict[str, Any]:
        """将ConfigParser对象转换为字典
        
        Args:
            config_parser: ConfigParser对象
            
        Returns:
            Dict[str, Any]: 配置字典
        """
        result = {}
        
        for section in config_parser.sections():
            result[section] = {}
            for key, value in config_parser.items(section):
                # 尝试转换值的类型
                result[section][key] = self._convert_value(value)
        
        # 添加默认节
        for key, value in config_parser.defaults().items():
            result[key] = self._convert_value(value)
        
        return result
    
    def _dict_to_configparser(self, config_dict: Dict[str, Any]) -> configparser.ConfigParser:
        """将字典转换为ConfigParser对象
        
        Args:
            config_dict: 配置字典
            
        Returns:
            configparser.ConfigParser: ConfigParser对象
        """
        config_parser = configparser.ConfigParser()
        
        # 添加所有节
        for section, items in config_dict.items():
            if isinstance(items, dict):
                config_parser.add_section(section)
                for key, value in items.items():
                    # 将值转换为字符串
                    config_parser.set(section, key, str(value))
            else:
                # 添加到默认节
                config_parser.set(configparser.DEFAULTSECT, section, str(items))
        
        return config_parser
    
    def _convert_value(self, value: str) -> Any:
        """尝试将字符串值转换为相应的类型
        
        Args:
            value: 字符串值
            
        Returns:
            Any: 转换后的值
        """
        # 尝试转换为布尔值
        if value.lower() in ('true', 'yes', 'y', '1'):
            return True
        if value.lower() in ('false', 'no', 'n', '0'):
            return False
        
        # 尝试转换为整数
        try:
            return int(value)
        except ValueError:
            pass
        
        # 尝试转换为浮点数
        try:
            return float(value)
        except ValueError:
            pass
        
        # 尝试转换为空值
        if value.lower() in ('none', 'null', ''):
            return None
        
        # 尝试转换为列表
        if value.startswith('[') and value.endswith(']'):
            try:
                return json.loads(value)
            except json.JSONDecodeError:
                pass
        
        # 默认返回字符串
        return value
    
    def export_config(self, format_type: str = 'json') -> str:
        """导出配置为字符串
        
        Args:
            format_type: 导出格式（json/yaml）
            
        Returns:
            str: 配置字符串
        """
        with self._lock:
            if format_type == 'json':
                return json.dumps(self._config, ensure_ascii=False, indent=2)
            elif format_type == 'yaml':
                return yaml.dump(self._config, allow_unicode=True, default_flow_style=False)
            else:
                raise ValueError(f"Unsupported export format: {format_type}")
    
    def import_config(self, config_str: str, format_type: str = 'json') -> None:
        """从字符串导入配置
        
        Args:
            config_str: 配置字符串
            format_type: 导入格式（json/yaml）
        """
        try:
            if format_type == 'json':
                imported_config = json.loads(config_str)
            elif format_type == 'yaml':
                imported_config = yaml.safe_load(config_str)
            else:
                raise ValueError(f"Unsupported import format: {format_type}")
            
            with self._lock:
                # 合并导入的配置
                self._merge_config(self._config, imported_config)
                
                # 验证配置
                self._validate_config()
                
                # 触发变更事件
                self._notify_change_listeners()
        except (json.JSONDecodeError, yaml.YAMLError) as e:
            raise ConfigParseError(f"Failed to parse imported config: {str(e)}")
        except Exception as e:
            raise ConfigParseError(f"Failed to import config: {str(e)}")
    
    def get_config_diff(self, other_config: Dict[str, Any]) -> Dict[str, Tuple[Any, Any]]:
        """获取当前配置与另一配置的差异
        
        Args:
            other_config: 另一配置字典
            
        Returns:
            Dict[str, Tuple[Any, Any]]: 差异字典，键为配置项，值为(当前值, 其他值)
        """
        diff = {}
        
        # 获取所有键
        current_keys = set(self.get_keys())
        other_keys = set(self._get_all_keys_from_dict(other_config))
        
        # 合并所有键
        all_keys = current_keys.union(other_keys)
        
        # 比较每个键的值
        for key in all_keys:
            current_value = self.get(key)
            other_value = self._get_value_from_dict(other_config, key)
            
            if current_value != other_value:
                diff[key] = (current_value, other_value)
        
        return diff
    
    def _get_all_keys_from_dict(self, config: Dict[str, Any], prefix: str = '', separator: str = '.') -> List[str]:
        """从字典中获取所有键名
        
        Args:
            config: 配置字典
            prefix: 当前前缀
            separator: 嵌套键分隔符
            
        Returns:
            List[str]: 键名列表
        """
        result = []
        
        for key, value in config.items():
            full_key = f"{prefix}{separator}{key}" if prefix else key
            
            if isinstance(value, dict):
                # 递归获取嵌套字典的键名
                result.extend(self._get_all_keys_from_dict(value, full_key, separator))
            else:
                # 添加键名到结果列表
                result.append(full_key)
        
        return result
    
    def _get_value_from_dict(self, config: Dict[str, Any], key: str, separator: str = '.') -> Any:
        """从字典中获取配置项的值
        
        Args:
            config: 配置字典
            key: 配置项键名
            separator: 嵌套键分隔符
            
        Returns:
            Any: 配置项的值
        """
        # 解析键名
        keys = key.split(separator)
        
        # 遍历嵌套配置
        current = config
        for k in keys:
            if isinstance(current, dict) and k in current:
                current = current[k]
            else:
                return None
        
        return current
    
    def copy(self) -> 'ConfigManager':
        """创建配置管理器的副本
        
        Returns:
            ConfigManager: 配置管理器副本
        """
        new_config_manager = ConfigManager(self._config_dir, self._default_config)
        
        with self._lock:
            new_config_manager._config = copy.deepcopy(self._config)
            new_config_manager._config_file_path = self._config_file_path
            new_config_manager._validators = self._validators.copy()
            # 不复制监听器
        
        return new_config_manager


class ConfigValidator:
    """配置验证器类，提供常用的验证函数"""
    
    @staticmethod
    def is_required(value: Any) -> bool:
        """验证值是否存在且不为空
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        return value is not None and value != ''
    
    @staticmethod
    def is_type(type_: type) -> Callable:
        """验证值是否为指定类型
        
        Args:
            type_: 类型
            
        Returns:
            Callable: 验证函数
        """
        def validator(value: Any) -> bool:
            return isinstance(value, type_)
        
        return validator
    
    @staticmethod
    def is_string(value: Any) -> bool:
        """验证值是否为字符串
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        return isinstance(value, str)
    
    @staticmethod
    def is_integer(value: Any) -> bool:
        """验证值是否为整数
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        return isinstance(value, int)
    
    @staticmethod
    def is_float(value: Any) -> bool:
        """验证值是否为浮点数
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        return isinstance(value, float)
    
    @staticmethod
    def is_boolean(value: Any) -> bool:
        """验证值是否为布尔值
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        return isinstance(value, bool)
    
    @staticmethod
    def is_list(value: Any) -> bool:
        """验证值是否为列表
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        return isinstance(value, list)
    
    @staticmethod
    def is_dict(value: Any) -> bool:
        """验证值是否为字典
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        return isinstance(value, dict)
    
    @staticmethod
    def is_none(value: Any) -> bool:
        """验证值是否为None
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        return value is None
    
    @staticmethod
    def is_in(values: List[Any]) -> Callable:
        """验证值是否在指定列表中
        
        Args:
            values: 有效值列表
            
        Returns:
            Callable: 验证函数
        """
        def validator(value: Any) -> bool:
            return value in values
        
        return validator
    
    @staticmethod
    def is_not_in(values: List[Any]) -> Callable:
        """验证值是否不在指定列表中
        
        Args:
            values: 无效值列表
            
        Returns:
            Callable: 验证函数
        """
        def validator(value: Any) -> bool:
            return value not in values
        
        return validator
    
    @staticmethod
    def is_range(min_value: Any = None, max_value: Any = None, inclusive: bool = True) -> Callable:
        """验证值是否在指定范围内
        
        Args:
            min_value: 最小值
            max_value: 最大值
            inclusive: 是否包含边界
            
        Returns:
            Callable: 验证函数
        """
        def validator(value: Any) -> bool:
            try:
                if inclusive:
                    if min_value is not None and value < min_value:
                        return False
                    if max_value is not None and value > max_value:
                        return False
                else:
                    if min_value is not None and value <= min_value:
                        return False
                    if max_value is not None and value >= max_value:
                        return False
                return True
            except (TypeError, ValueError):
                return False
        
        return validator
    
    @staticmethod
    def is_length(min_length: int = None, max_length: int = None) -> Callable:
        """验证值的长度是否在指定范围内
        
        Args:
            min_length: 最小长度
            max_length: 最大长度
            
        Returns:
            Callable: 验证函数
        """
        def validator(value: Any) -> bool:
            try:
                length = len(value)
                if min_length is not None and length < min_length:
                    return False
                if max_length is not None and length > max_length:
                    return False
                return True
            except (TypeError, ValueError):
                return False
        
        return validator
    
    @staticmethod
    def matches_regex(pattern: str) -> Callable:
        """验证值是否匹配正则表达式
        
        Args:
            pattern: 正则表达式
            
        Returns:
            Callable: 验证函数
        """
        import re
        
        def validator(value: Any) -> bool:
            try:
                return re.match(pattern, str(value)) is not None
            except (TypeError, ValueError):
                return False
        
        return validator
    
    @staticmethod
    def is_file_path(value: Any) -> bool:
        """验证值是否为有效的文件路径
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        try:
            return isinstance(value, str) and os.path.isfile(value)
        except (TypeError, ValueError):
            return False
    
    @staticmethod
    def is_dir_path(value: Any) -> bool:
        """验证值是否为有效的目录路径
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        try:
            return isinstance(value, str) and os.path.isdir(value)
        except (TypeError, ValueError):
            return False
    
    @staticmethod
    def is_readable_file(value: Any) -> bool:
        """验证值是否为可读的文件路径
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        try:
            if not isinstance(value, str) or not os.path.isfile(value):
                return False
            # 尝试打开文件以检查可读性
            with open(value, 'r') as f:
                return True
        except (TypeError, ValueError, IOError, PermissionError):
            return False
    
    @staticmethod
    def is_writable_file(value: Any) -> bool:
        """验证值是否为可写的文件路径
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        try:
            if not isinstance(value, str):
                return False
            
            # 如果文件已存在，检查是否可写
            if os.path.exists(value):
                if not os.path.isfile(value):
                    return False
                # 尝试打开文件以检查可写性
                with open(value, 'a') as f:
                    return True
            else:
                # 检查目录是否存在且可写
                dir_path = os.path.dirname(value)
                if dir_path and not os.path.exists(dir_path):
                    # 尝试创建目录
                    try:
                        os.makedirs(dir_path, exist_ok=True)
                    except (IOError, PermissionError):
                        return False
                elif dir_path and not os.access(dir_path, os.W_OK):
                    return False
                
                # 尝试创建文件
                try:
                    with open(value, 'w') as f:
                        pass
                    # 删除测试文件
                    os.remove(value)
                    return True
                except (IOError, PermissionError):
                    return False
        except (TypeError, ValueError):
            return False
    
    @staticmethod
    def is_valid_email(value: Any) -> bool:
        """验证值是否为有效的电子邮件地址
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        import re
        
        try:
            if not isinstance(value, str):
                return False
            
            # 简单的电子邮件正则表达式
            pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
            return re.match(pattern, value) is not None
        except (TypeError, ValueError):
            return False
    
    @staticmethod
    def is_valid_url(value: Any) -> bool:
        """验证值是否为有效的URL
        
        Args:
            value: 要验证的值
            
        Returns:
            bool: 是否通过验证
        """
        import re
        
        try:
            if not isinstance(value, str):
                return False
            
            # 简单的URL正则表达式
            pattern = r"^(https?://)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*/?$"
            return re.match(pattern, value) is not None
        except (TypeError, ValueError):
            return False
    
    @staticmethod
    def all_of(*validators: Callable) -> Callable:
        """组合多个验证器，所有验证器都通过才返回True
        
        Args:
            *validators: 验证器函数列表
            
        Returns:
            Callable: 组合后的验证函数
        """
        def validator(value: Any) -> bool:
            return all(v(value) for v in validators)
        
        return validator
    
    @staticmethod
    def any_of(*validators: Callable) -> Callable:
        """组合多个验证器，任何一个验证器通过就返回True
        
        Args:
            *validators: 验证器函数列表
            
        Returns:
            Callable: 组合后的验证函数
        """
        def validator(value: Any) -> bool:
            return any(v(value) for v in validators)
        
        return validator
    
    @staticmethod
    def not_(validator: Callable) -> Callable:
        """取反验证器的结果
        
        Args:
            validator: 验证器函数
            
        Returns:
            Callable: 取反后的验证函数
        """
        def not_validator(value: Any) -> bool:
            return not validator(value)
        
        return not_validator


class ConfigCache:
    """配置缓存类，用于缓存配置项的值"""
    
    def __init__(self, config_manager: ConfigManager, ttl: Optional[int] = None):
        """初始化配置缓存
        
        Args:
            config_manager: 配置管理器
            ttl: 缓存过期时间（秒），None表示永不过期
        """
        self._config_manager = config_manager
        self._ttl = ttl
        self._cache: Dict[str, Tuple[Any, float]] = {}
        self._lock = threading.RLock()
        
        # 添加配置变更监听器，当配置变更时清除缓存
        self._config_manager.add_change_listener(self.clear)
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取缓存的配置项值
        
        Args:
            key: 配置项键名
            default: 默认值
            
        Returns:
            Any: 配置项的值或默认值
        """
        import time
        
        with self._lock:
            # 检查缓存是否存在且未过期
            if key in self._cache:
                value, timestamp = self._cache[key]
                
                # 检查是否过期
                if self._ttl is None or time.time() - timestamp < self._ttl:
                    return value
                
                # 过期了，从缓存中删除
                del self._cache[key]
            
            # 从配置管理器获取值
            value = self._config_manager.get(key, default)
            
            # 添加到缓存
            self._cache[key] = (value, time.time())
            
            return value
    
    def set(self, key: str, value: Any) -> None:
        """设置缓存的配置项值
        
        Args:
            key: 配置项键名
            value: 配置项的值
        """
        import time
        
        with self._lock:
            self._cache[key] = (value, time.time())
    
    def remove(self, key: str) -> bool:
        """从缓存中移除配置项
        
        Args:
            key: 配置项键名
            
        Returns:
            bool: 是否移除成功
        """
        with self._lock:
            if key in self._cache:
                del self._cache[key]
                return True
            return False
    
    def clear(self) -> None:
        """清空缓存"""
        with self._lock:
            self._cache.clear()
    
    def has(self, key: str) -> bool:
        """检查缓存中是否存在配置项
        
        Args:
            key: 配置项键名
            
        Returns:
            bool: 是否存在
        """
        import time
        
        with self._lock:
            if key in self._cache:
                # 检查是否过期
                _, timestamp = self._cache[key]
                if self._ttl is None or time.time() - timestamp < self._ttl:
                    return True
                
                # 过期了，从缓存中删除
                del self._cache[key]
            
            return False
    
    def get_cache_size(self) -> int:
        """获取缓存大小
        
        Returns:
            int: 缓存中的配置项数量
        """
        import time
        
        with self._lock:
            # 清理过期的缓存项
            if self._ttl is not None:
                current_time = time.time()
                expired_keys = [
                    key for key, (_, timestamp) in self._cache.items()
                    if current_time - timestamp >= self._ttl
                ]
                
                for key in expired_keys:
                    del self._cache[key]
            
            return len(self._cache)
    
    def set_ttl(self, ttl: Optional[int]) -> None:
        """设置缓存过期时间
        
        Args:
            ttl: 缓存过期时间（秒），None表示永不过期
        """
        self._ttl = ttl
    
    def get_ttl(self) -> Optional[int]:
        """获取缓存过期时间
        
        Returns:
            Optional[int]: 缓存过期时间（秒）
        """
        return self._ttl


# 创建全局配置管理器实例
def get_default_config_manager() -> ConfigManager:
    """获取默认的配置管理器实例
    
    Returns:
        ConfigManager: 配置管理器实例
    """
    # 定义默认配置
    default_config = {
        'editor': {
            'font': {
                'family': 'Consolas',
                'size': 12
            },
            'theme': 'default',
            'tab_size': 4,
            'indent_size': 4,
            'use_spaces': True,
            'auto_indent': True,
            'line_numbers': True,
            'highlight_current_line': True,
            'word_wrap': False,
            'show_whitespace': False,
            'auto_complete': True,
            'code_folding': True,
            'brace_matching': True
        },
        'designer': {
            'default_width': 800,
            'default_height': 600,
            'grid_size': 10,
            'show_grid': True,
            'snap_to_grid': True,
            'default_margins': 10,
            'preview_scale': 1.0
        },
        'build': {
            'output_dir': 'build',
            'build_command': 'python -m build',
            'clean_before_build': True,
            'verbose': False
        },
        'run': {
            'command': 'python main.py',
            'working_dir': '.',
            'environment': {},
            'debug': False
        },
        'debug': {
            'port': 5678,
            'host': 'localhost',
            'break_on_exception': True,
            'break_on_first_line': False,
            'auto_continue': False
        },
        'ui': {
            'theme': 'light',
            'show_toolbar': True,
            'show_statusbar': True,
            'show_sidebar': True,
            'sidebar_width': 250,
            'remember_window_size': True,
            'remember_window_position': True,
            'window_width': 1200,
            'window_height': 800
        },
        'recent_files': [],
        'recent_projects': [],
        'max_recent_items': 10,
        'language': 'auto'
    }
    
    # 创建配置管理器
    config_manager = ConfigManager(default_config=default_config)
    
    # 注册验证器
    validator = ConfigValidator()
    
    # 编辑器配置验证
    config_manager.register_validator('editor.font.family', validator.is_string)
    config_manager.register_validator('editor.font.size', validator.all_of(validator.is_integer, validator.is_range(6, 72)))
    config_manager.register_validator('editor.tab_size', validator.all_of(validator.is_integer, validator.is_range(2, 16)))
    config_manager.register_validator('editor.indent_size', validator.all_of(validator.is_integer, validator.is_range(2, 16)))
    config_manager.register_validator('editor.use_spaces', validator.is_boolean)
    config_manager.register_validator('editor.auto_indent', validator.is_boolean)
    config_manager.register_validator('editor.line_numbers', validator.is_boolean)
    config_manager.register_validator('editor.highlight_current_line', validator.is_boolean)
    config_manager.register_validator('editor.word_wrap', validator.is_boolean)
    config_manager.register_validator('editor.show_whitespace', validator.is_boolean)
    config_manager.register_validator('editor.auto_complete', validator.is_boolean)
    config_manager.register_validator('editor.code_folding', validator.is_boolean)
    config_manager.register_validator('editor.brace_matching', validator.is_boolean)
    
    # 设计器配置验证
    config_manager.register_validator('designer.default_width', validator.all_of(validator.is_integer, validator.is_range(200, 3200)))
    config_manager.register_validator('designer.default_height', validator.all_of(validator.is_integer, validator.is_range(200, 2400)))
    config_manager.register_validator('designer.grid_size', validator.all_of(validator.is_integer, validator.is_range(5, 50)))
    config_manager.register_validator('designer.show_grid', validator.is_boolean)
    config_manager.register_validator('designer.snap_to_grid', validator.is_boolean)
    config_manager.register_validator('designer.default_margins', validator.all_of(validator.is_integer, validator.is_range(0, 100)))
    config_manager.register_validator('designer.preview_scale', validator.is_range(0.1, 5.0))
    
    # 构建配置验证
    config_manager.register_validator('build.output_dir', validator.is_string)
    config_manager.register_validator('build.build_command', validator.is_string)
    config_manager.register_validator('build.clean_before_build', validator.is_boolean)
    config_manager.register_validator('build.verbose', validator.is_boolean)
    
    # 运行配置验证
    config_manager.register_validator('run.command', validator.is_string)
    config_manager.register_validator('run.working_dir', validator.is_string)
    config_manager.register_validator('run.debug', validator.is_boolean)
    
    # 调试配置验证
    config_manager.register_validator('debug.port', validator.all_of(validator.is_integer, validator.is_range(1024, 65535)))
    config_manager.register_validator('debug.host', validator.is_string)
    config_manager.register_validator('debug.break_on_exception', validator.is_boolean)
    config_manager.register_validator('debug.break_on_first_line', validator.is_boolean)
    config_manager.register_validator('debug.auto_continue', validator.is_boolean)
    
    # UI配置验证
    config_manager.register_validator('ui.theme', validator.is_in(['light', 'dark', 'system']))
    config_manager.register_validator('ui.show_toolbar', validator.is_boolean)
    config_manager.register_validator('ui.show_statusbar', validator.is_boolean)
    config_manager.register_validator('ui.show_sidebar', validator.is_boolean)
    config_manager.register_validator('ui.sidebar_width', validator.all_of(validator.is_integer, validator.is_range(100, 1000)))
    config_manager.register_validator('ui.remember_window_size', validator.is_boolean)
    config_manager.register_validator('ui.remember_window_position', validator.is_boolean)
    config_manager.register_validator('ui.window_width', validator.all_of(validator.is_integer, validator.is_range(600, 3200)))
    config_manager.register_validator('ui.window_height', validator.all_of(validator.is_integer, validator.is_range(400, 2400)))
    
    # 最近文件和项目配置验证
    config_manager.register_validator('recent_files', validator.is_list)
    config_manager.register_validator('recent_projects', validator.is_list)
    config_manager.register_validator('max_recent_items', validator.all_of(validator.is_integer, validator.is_range(1, 50)))
    
    # 语言配置验证
    config_manager.register_validator('language', validator.is_string)
    
    return config_manager


# 创建全局配置管理器实例
global_config_manager = get_default_config_manager()


# 导出常用函数
def get_config(key: str, default: Any = None) -> Any:
    """获取全局配置项的值
    
    Args:
        key: 配置项键名
        default: 默认值
        
    Returns:
        Any: 配置项的值或默认值
    """
    return global_config_manager.get(key, default)

def set_config(key: str, value: Any) -> None:
    """设置全局配置项的值
    
    Args:
        key: 配置项键名
        value: 配置项的值
    """
    global_config_manager.set(key, value)

def load_config(config_file: str) -> bool:
    """加载全局配置
    
    Args:
        config_file: 配置文件路径
        
    Returns:
        bool: 是否加载成功
    """
    return global_config_manager.load(config_file)

def save_config(config_file: Optional[str] = None) -> bool:
    """保存全局配置
    
    Args:
        config_file: 配置文件路径，如果为None则使用上次加载的路径
        
    Returns:
        bool: 是否保存成功
    """
    return global_config_manager.save(config_file)

def reset_config() -> None:
    """重置全局配置为默认值"""
    global_config_manager.reset()

def add_config_change_listener(listener: Callable) -> None:
    """添加全局配置变更监听器
    
    Args:
        listener: 监听器函数
    """
    global_config_manager.add_change_listener(listener)

def remove_config_change_listener(listener: Callable) -> None:
    """移除全局配置变更监听器
    
    Args:
        listener: 监听器函数
    """
    global_config_manager.remove_change_listener(listener)